import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/foundation.dart';
import '../models/user.dart';

/// Web环境专用的认证服务
/// 解决Flutter Web的CORS和网络连接问题
class WebAuthService {
  static const String baseUrl = 'http://127.0.0.1:5000/api';
  static const String tokenKey = 'auth_token';

  final Dio _dio = Dio();

  WebAuthService() {
    _dio.options.baseUrl = baseUrl;
    _dio.options.headers['Content-Type'] = 'application/json';
    _dio.options.connectTimeout = const Duration(seconds: 15);
    _dio.options.receiveTimeout = const Duration(seconds: 15);

    // Web环境特殊配置
    _dio.options.headers['Accept'] = 'application/json';

    // 添加请求和响应拦截器用于调试
    _dio.interceptors.add(
      LogInterceptor(
        requestBody: true,
        responseBody: true,
        error: true,
        logPrint: (object) {
          if (kDebugMode) {
            print('🌐 WebAuth API: $object');
          }
        },
      ),
    );

    // 错误处理拦截器
    _dio.interceptors.add(
      InterceptorsWrapper(
        onError: (error, handler) {
          if (kDebugMode) {
            print('❌ WebAuth网络错误: ${error.type} - ${error.message}');
            print('❌ 请求URL: ${error.requestOptions.uri}');
            print('❌ 响应状态: ${error.response?.statusCode}');
          }
          handler.next(error);
        },
      ),
    );
  }

  Future<String?> getToken() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(tokenKey);
  }

  Future<void> saveToken(String token) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(tokenKey, token);
  }

  Future<void> clearToken() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(tokenKey);
  }

  /// 测试后端连接
  Future<bool> testConnection() async {
    try {
      print('🔍 测试后端连接: $baseUrl');

      final response = await _dio.get(
        '/health',
        options: Options(
          sendTimeout: const Duration(seconds: 5),
          receiveTimeout: const Duration(seconds: 5),
        ),
      );

      print('✅ 连接测试成功: ${response.statusCode}');
      return response.statusCode == 200;
    } catch (e) {
      print('❌ 连接测试失败: $e');
      return false;
    }
  }

  Future<User> login(String email, String password) async {
    try {
      print('🔐 Web登录尝试: $email');

      // 先测试连接
      final isConnected = await testConnection();
      if (!isConnected) {
        throw Exception('无法连接到服务器，请确保后端服务正在运行');
      }

      final response = await _dio.post(
        '/auth/login',
        data: {'email': email, 'password': password},
        options: Options(
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
        ),
      );

      print('📡 登录响应: ${response.statusCode} - ${response.data}');

      if (response.statusCode == 200 && response.data['success'] == true) {
        final token = response.data['token'];
        final userData = response.data['user'];
        final user = User.fromJson(userData);

        await saveToken(token);
        print('✅ Web登录成功');
        return user;
      } else {
        throw Exception(response.data['message'] ?? '登录失败');
      }
    } on DioException catch (e) {
      print('🚨 WebAuth Dio异常: ${e.type} - ${e.message}');

      if (e.type == DioExceptionType.connectionError) {
        throw Exception(
          '网络连接失败\n'
          '请确保：\n'
          '1. 后端服务器正在运行在 localhost:5000\n'
          '2. 网络连接正常\n'
          '3. 防火墙没有阻止连接',
        );
      } else if (e.type == DioExceptionType.connectionTimeout) {
        throw Exception('连接超时，请检查网络或服务器状态');
      } else if (e.type == DioExceptionType.receiveTimeout) {
        throw Exception('请求超时，请重试');
      } else if (e.response?.statusCode == 401) {
        throw Exception('邮箱或密码错误');
      } else if (e.response?.statusCode == 404) {
        throw Exception('API接口不存在，请检查后端服务');
      } else {
        throw Exception('网络错误: ${e.message ?? '未知错误'}');
      }
    } catch (e) {
      print('❌ Web登录错误: $e');
      throw Exception('登录失败: $e');
    }
  }

  Future<User> register(String name, String email, String password) async {
    try {
      print('📝 Web注册尝试: $email');

      final response = await _dio.post(
        '/auth/register',
        data: {'name': name, 'email': email, 'password': password},
        options: Options(
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
        ),
      );

      print('📡 注册响应: ${response.statusCode} - ${response.data}');

      if (response.statusCode == 201 && response.data['success'] == true) {
        final token = response.data['token'];
        final userData = response.data['user'];
        final user = User.fromJson(userData);

        await saveToken(token);
        print('✅ Web注册成功');
        return user;
      } else {
        throw Exception(response.data['message'] ?? '注册失败');
      }
    } on DioException catch (e) {
      print('🚨 WebAuth注册异常: ${e.type} - ${e.message}');

      if (e.response?.statusCode == 409) {
        throw Exception('用户已存在');
      } else if (e.type == DioExceptionType.connectionError) {
        throw Exception('网络连接失败，请检查网络设置');
      } else if (e.type == DioExceptionType.connectionTimeout) {
        throw Exception('连接超时，请检查网络连接');
      } else if (e.type == DioExceptionType.receiveTimeout) {
        throw Exception('请求超时，请重试');
      } else {
        throw Exception('网络错误: ${e.message ?? '请检查网络连接'}');
      }
    } catch (e) {
      print('❌ Web注册错误: $e');
      throw Exception('注册失败: $e');
    }
  }

  Future<void> logout() async {
    await clearToken();
  }

  Future<bool> isLoggedIn() async {
    final token = await getToken();
    return token != null && token.isNotEmpty;
  }

  // 更新用户资料
  Future<User?> updateProfile({
    required String name,
    String? bio,
    String? phone,
    String? location,
  }) async {
    try {
      final token = await getToken();
      if (token == null) {
        throw Exception('未找到认证令牌');
      }

      print('🔄 WebAuth更新用户资料: $name, $bio, $phone, $location');

      final response = await _dio.put(
        '/users/profile',
        data: {'name': name, 'bio': bio, 'phone': phone, 'location': location},
        options: Options(headers: {'Authorization': 'Bearer $token'}),
      );

      print('🔄 WebAuth更新响应: ${response.statusCode} - ${response.data}');

      if (response.statusCode == 200) {
        final data = response.data;
        if (data['success'] == true && data['data'] != null) {
          return User.fromJson(data['data']['user']);
        }
      }

      throw Exception('更新失败');
    } on DioException catch (e) {
      print('🚨 WebAuth更新用户资料网络异常: ${e.type} - ${e.message}');

      if (e.response?.statusCode == 401) {
        throw Exception('认证失败，请重新登录');
      } else if (e.response?.statusCode == 404) {
        throw Exception('用户不存在');
      } else if (e.type == DioExceptionType.connectionError) {
        throw Exception('无法连接到服务器');
      } else {
        throw Exception('网络错误: ${e.message ?? '请检查网络连接'}');
      }
    } catch (e) {
      print('🚨 WebAuth更新用户资料失败: $e');
      rethrow;
    }
  }
}
